import { ApiResponse, LoginForm, Token } from "@/types/data";
import { LoginAction, RootThunkAction } from "@/types/store";
import request from "@/utils/request";
import { removeToken, setToken } from "@/utils/storage";

export function login(values: LoginForm): RootThunkAction {
  return async (dispatch) => {
    const res = await request.post<ApiResponse<Token>>('/authorizations', values);
    dispatch({
      type: 'login/login',
      payload: res.data.data
    });
    //将Token保存在本地localstorate
    setToken(res.data.data);
  }
}

export function getCode(mobile: string): RootThunkAction {
  return async () => {
    await request.get(`/sms/codes/${mobile}`);
    //注意： 验证码是发送到手机上的，不需要更新Redux的状态
  }
}

export function logout(): LoginAction {
  removeToken();
  return {
    type: 'login/logout'
  }
}